package com.eam.eventhandler;

import com.eam.data.EamCheckPlanItem;
import org.hibernate.Query;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.EntityDeleteEvent;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.database.SessionInfo;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import javax.enterprise.event.Observes;

public class FacilitiesDetailsEventHandler extends EntityPersistenceEventObserver {
	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EamCheckPlanItem.ENTITY_NAME) };

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}

	public void onUpdate(@Observes EntityUpdateEvent event) throws Throwable {
		if (!isValidEvent(event)) {
			return;
		}

	}
	
	//新增
	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
		String tabId = SessionInfo.getProcessId();

		if (tabId == null) {
			return;
		}

		// 获取计划
		EamCheckPlanItem details = (EamCheckPlanItem) event.getTargetInstance();
		// 将要更改的实体类
		final Entity detailsEntity = ModelProvider.getInstance().getEntity(EamCheckPlanItem.ENTITY_NAME);
		EamCheckPlanItem old_item = null;

		// 获取item
		String i_id = details.getEamCheckPlanFacilities().getId();
		String status = details.getEamCheckPlanFacilities().getStatus();
		String d_id = "";
		
		if(status.equals("OK")){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, (details.getEamCheckPlanFacilities().getEamFacilities().getName())+ "设备已经点检完毕，请仔细检查", language));
		}else{
			d_id = details.getEamCheckItem().getId();
			String hql = "select empd from " + EamCheckPlanItem.ENTITY_NAME + " empd where empd.eamCheckPlanFacilities.id =:i_id and empd.eamCheckItem.id =:d_id ";
			Query query = OBDal.getInstance().getSession().createQuery(hql);
			query.setString("i_id", i_id);
			query.setString("d_id", d_id);
			old_item = (EamCheckPlanItem) query.uniqueResult();
		

			if (old_item != null) {
				String language = OBContext.getOBContext().getLanguage().getLanguage();
				ConnectionProvider conn = new DalConnectionProvider(false);
				throw new OBException(Utility.messageBD(conn, (details.getEamCheckItem().getName())
								+ "已经添加，请仔细检查", language));
			}
		}
		

	}

	public void onDelete(@Observes EntityDeleteEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
	}

}
